/**
 * 小程序入口文件
 * 负责应用初始化和全局状态管理
 */

const AppConfig = require('./config/app.config');
const logger = require('./utils/logger').logger;
const realLog = require('./utils/realLog');
//const BluetoothService = require('./services/bluetooth-service').getInstance;
const DeviceService = require('./services/device-service').getInstance;
const wxPolyfill = require('./utils/wx-polyfill');
const workerPolyfill = require('./utils/worker-polyfill');
const workerManager = require('./utils/worker-manager');
const networkManager = require('./utils/network-manager');
const envDetector = require('./utils/env-detector');

// 添加全局存储服务引用
const storageService = require('./services/storage');

// 设备类型模块注册
const deviceModules = {
  'freshwater_lamp': require('./services/main'),
  'seawater_lamp': require('./services/main'),
  'freshwater_diy_lamp': require('./services/main'),
  'seawater_diy_lamp': require('./services/main')
};

// 全局空函数，用于拦截不支持的API调用
const noop = function () {};

// 应用所有微信API兼容性修复
wxPolyfill.runAllFixes();
// 应用所有Worker环境的兼容性修复
try {
  workerPolyfill.runAllFixes();
} catch (e) {
  console.log('Worker polyfill初始化失败，可能不在Worker环境中', e);
}


import './utils/eventBus';
import mqtt from './utils/mqtt.min'; //加载mqtt库
import * as comm from './utils/common';


const tempArr = [28.0170, 26.8255, 25.6972, 24.6290, 23.6176, 22.6597, 21.7522, 20.8916, 20.0749, 19.2988, 18.5600,
  18.4818, 18.1489, 17.6316, 16.9917, 16.2797, 15.5350, 14.7867, 14.0551, 13.3536, 12.6900, 12.0684, 11.4900, 10.9539,
  10.4582, 10.0000, 9.5762, 9.1835, 8.8186, 8.4784, 8.1600, 7.8608, 7.5785, 7.3109, 7.0564, 6.8133, 6.5806, 6.3570,
  6.1418, 5.9343, 5.7340, 5.5405, 5.3534, 5.1725, 4.9976, 4.8286, 4.6652, 4.5073, 4.3548, 4.2075, 4.0650, 3.9271,
  3.7936, 3.6639, 3.5377, 3.4146, 3.2939, 3.1752, 3.0579, 2.9414, 2.8250, 2.7762, 2.7179, 2.6523, 2.5817, 2.5076, 2.4319, 2.3557, 2.2803, 2.2065, 2.1350, 2.0661, 2.0004, 1.9378, 1.8785, 1.8225, 1.7696, 1.7197, 1.6727, 1.6282, 1.5860, 1.5458, 1.5075, 1.4707, 1.4352, 1.4006, 1.3669, 1.3337, 1.3009, 1.2684, 1.2360, 1.2037, 1.1714, 1.1390, 1.1067, 1.0744, 1.0422, 1.0104, 0.9789, 0.9481, 0.9180


];

const domain = "https://www.99666666.xyz";

const msgKeyMap = ["", "sT", "sRun", "tRun", "tempStart", "tempDiff", "tempNow", "time", "handing", "v", "fanStarted", "hasV"];

function loginFunction(that) {
  let promise;
  if (comm.isEmpty(that.globalData.openid)) {
    promise = new Promise((resolve, reject) => {
      wx.login({
        success: function (res) {
          console.log("usercode=" + res.code);
          comm.httpGet("/wuser/login?code=" + res.code, function (res) {
            resolve(res);
          }, function (errMsg) {
            reject(errMsg);
          });
        },
        fail(error) {
          reject(error)
        }
      })
    });
  } else {
    promise = new Promise((resolve, reject) => {
      comm.httpGet("/wuser/login?oid=" + that.globalData.openid, function (res) {
        resolve(res);
      }, function (errMsg) {
        reject(errMsg);
      });
    });
  }
  return promise;
}


App({
  /**
   * 应用初始化
   */
  onLaunch: function () {
    // 检测是否在开发者工具中运行
    this.globalData.isDevTools = envDetector.isDevTools();
    logger.info('应用启动', {
      version: AppConfig.APP.VERSION,
      isDevTools: this.globalData.isDevTools
    });

    if (this.globalData.isDevTools) {
      logger.info('在开发者工具中运行，部分API将使用模拟模式');
    }

    // 检查更新
    this.checkUpdate();

    // 初始化系统信息
    this.initSystemInfo();

    // 加载应用配置
    this.loadAppSettings();

    // 设置调试模式
    this.setDebugMode();

    // 修复存储数据格式
    //this.fixStorageDataFormat();

    // 初始化设备服务
    //this.initDeviceService();

    // 初始化网络监听
    //this.initNetworkListening();





    const $t = this;
    $t.globalData.openid = storageService.getOpenid()
    $t.globalData.sid = storageService.getSid()
    $t.globalData.mtid = $t.globalData.openid

    const windowInfo = wx.getWindowInfo();
    $t.globalData.pixelRatio = windowInfo.pixelRatio;
    $t.globalData.windowWidth = windowInfo.windowWidth;
    $t.globalData.windowHeight = windowInfo.windowHeight;
    const appBaseInfo = wx.getAppBaseInfo()
    $t.globalData.language = appBaseInfo.language;
    $t.globalData.version = appBaseInfo.version;
    $t.globalData.SDKVersion = appBaseInfo.SDKVersion;
    const deviceInfo = wx.getDeviceInfo()
    $t.globalData.model = deviceInfo.model;
    $t.globalData.platform = deviceInfo.platform;
    $t.globalData.brand = deviceInfo.brand;
    $t.globalData.system = deviceInfo.system;
    $t.globalData.isRelease = ("release" === wx.getAccountInfoSync().miniProgram.envVersion);
    console.log($t.globalData);
    this.initDeviceStatusMap();

    // 封装登录接口为一个Promise
    const loginPromise = new Promise((resolve, reject) => {
      // 调用登录接口
      loginFunction(this).then((res) => {
        // 登录成功时，执行 resolve
        console.log(res);
        let obj = res.data;
        if (comm.isEmpty(this.globalData.openid) || comm.isEmpty(this.globalData.sid)) {
          if (res.code == 0) {
            this.globalData.openid = obj.openid;
            this.globalData.sid = obj.sid;
            storageService.setOpenid(obj.openid)
            storageService.setSid(obj.sid)
          }
        }
        this.initMtConfig(obj);
        this.mtCfgInited = true;
        this.mqttConnect();
        resolve();
      }).catch((error) => {
        // 登录失败时，执行 reject
        this.mtCfgInited = true;
        this.mqttConnect();
        reject(error);
      });

    });
    // 将 loginPromise 作为一个全局变量
    this.globalData.loginPromise = loginPromise;
    this.globalData.logPre = this.globalData.sid + "|" + this.globalData.model + "|" + this.globalData.system + "|"
    this.log("app onLaunch...")
  },

  /**
   * 初始化设备服务
   */
  initDeviceService: function () {
    try {
      logger.info('初始化设备服务...');

      // 获取设备服务实例
      const deviceService = DeviceService();

      // 保存到全局数据中
      this.globalData.deviceService = deviceService;

      // 加载已保存的设备
      const savedDevices = wx.getStorageSync('deviceList') || [];
      if (savedDevices.length > 0) {
        logger.info(`正在注册${savedDevices.length}个已保存的设备`);

        savedDevices.forEach(device => {
          try {
            // 构建WiFi信息
            const wifiInfo = device.ssid ? {
              ssid: device.ssid,
              bssid: device.bssid || '',
              password: wx.getStorageSync(`wifi_password_${device.id}`) || ''
            } : null;

            // 注册设备
            deviceService.registerDevice(device.id, {
              deviceInfo: {
                name: device.name,
                type: device.deviceType,
                isFreshwater: device.deviceType.includes('freshwater'),
                isDIY: device.deviceType.includes('diy')
              },
              wifiInfo: wifiInfo,
              batteryLevel: device.batteryLevel || 100,
              onConnected: (info) => {
                logger.info(`设备[${device.id}]连接成功，连接模式: ${info.mode}`);
                this.updateDeviceStatus(device.id, true);
              },
              onDisconnected: (info) => {
                logger.warn(`设备[${device.id}]连接断开，连接模式: ${info ? info.mode : '未知'}`);
                this.updateDeviceStatus(device.id, false);
              },
              onFailed: (err) => {
                logger.error(`设备[${device.id}]连接失败`, err);
                this.updateDeviceStatus(device.id, false);
              }
            });
          } catch (e) {
            logger.error(`注册设备[${device.id}]失败`, e);
          }
        });
      } else {
        logger.info('没有已保存的设备');
      }
    } catch (e) {
      logger.error('初始化设备服务失败:', e);
    }
  },

  /**
   * 初始化网络监听
   * 用于处理网络状态变化，优化连接策略
   */
  initNetworkListening: function () {
    try {
      logger.info('初始化网络状态监听...');

      // 获取网络管理器实例
      const manager = networkManager;
      this.globalData.networkManager = manager;

      // 监听网络状态变化
      manager.startMonitoring({
        onChange: (networkType) => {
          try {
            logger.info(`网络状态变化: ${networkType}`);

            // 更新全局网络状态
            this.globalData.networkType = networkType;

            // 当网络状态变化时调整设备连接策略
            if (this.globalData.deviceService) {
              // 获取连接模式枚举
              const CONNECTION_MODE = DeviceService.CONNECTION_MODE;
              if (!CONNECTION_MODE) {
                logger.warn('无法获取连接模式枚举，跳过连接策略调整');
                return;
              }

              // 在WiFi网络环境下优先使用WiFi连接
              if (networkType === 'wifi') {
                this.globalData.deviceService.setConnectionMode(CONNECTION_MODE.AUTO);
              }
              // 其他网络环境下优先使用蓝牙连接以节省设备电量
              else {
                this.globalData.deviceService.setConnectionMode(CONNECTION_MODE.BLUETOOTH);
              }
            }
          } catch (e) {
            logger.error('处理网络状态变化失败', e);
          }
        }
      });
    } catch (e) {
      logger.error('初始化网络监听失败:', e);
    }
  },

  /**
   * 更新设备状态
   * @param {string} deviceId - 设备ID
   * @param {boolean} isOnline - 是否在线
   */
  updateDeviceStatus: function (deviceId, isOnline) {
    // 更新设备列表中的状态
    const devicesData = this.globalData.devices || [];
    const index = devicesData.findIndex(d => d.id === deviceId);

    if (index !== -1) {
      devicesData[index].status = isOnline ? '在线' : '离线';
      this.globalData.devices = devicesData;

      // 触发设备状态变化事件
      if (this.deviceStatusCallback) {
        this.deviceStatusCallback(devicesData);
      }
    }
  },

  /**
   * 根据设备类型获取对应的模块
   * @param {string} deviceType - 设备类型标识符
   * @returns {Object|null} 设备类型模块或null
   */
  getDeviceModule: function (deviceType) {
    if (!deviceType) return null;
    return deviceModules[deviceType] || null;
  },

  /**
   * 应用显示
   */
  onShow: function (options) {
    this.log("app onShow...")
    logger.info('应用进入前台', options);

    // 记录启动参数
    this.globalData.launchOptions = options;

    // 恢复应用状态
    this.resumeAppState();



    console.log("app onShow")
    const $t = this;
    clearTimeout($t.mtConnTimeout);
    if (!$t.mtClientInited && !$t.globalData.isAdding) {
      $t.mqttConnect();
    }

    $t.ckOnlineInterval = setInterval(() => {
      $t.handleOffline()
    }, 20000);
  },

  /**
   * 应用隐藏
   */
  onHide: function () {
    this.log("app onHide...")
    logger.info('应用进入后台');

    // 保存应用状态
    this.saveAppState();



    console.log("app onHide")
    const $t = this;
    if (!$t.globalData.isAdding) {
      $t.mtStop(1);
    }

    clearInterval($t.ckOnlineInterval)
    $t.ckOnlineInterval = null
  },


  deviceStatusMap: {
    /*"topicSubxxx": {
      "did": "",
      sRun: 0,
      tRun: "",
      syncType: 1,
      tempStart:0,
      tempDiff:0
    }*/
  },
  deviceVerMap: {
    /*"did":{"t":"V","v":10,"s":"1","ver":"V1.0_1"}*/
  },
  mtConnTimeout: null,
  mtConning: false,
  mtClient: null,
  mtClientInited: false,
  mtCfgInited: false,
  mtSubMap: {},
  mtSubTmp: [],
  mqttConnect() {
    const $t = this;
    if (!$t.mtCfgInited || $t.mtClientInited || $t.mtConning) {
      return;
    }
    $t.mtConning = true;
    //MQTT连接的配置
    var options = {
      keepalive: 10, //30s ，表示心跳间隔
      clean: true, //cleanSession不保持持久会话
      protocolVersion: 4, //MQTT v3.1.1
      clientId: $t.globalData.mtid,
      username: $t.globalData.username,
      password: $t.globalData.password,
      connectTimeout: 10000
    };
    //初始化mqtt连接
    console.log('开始连接服务器...' + new Date());
    this.log('开始连接服务器...')
    $t.mtClient = mqtt.connect($t.globalData.mtaddr, options)
    // 连接mqtt服务器
    $t.mtClient.on('connect', function () {
      console.log('连接服务器成功...' + new Date());
      $t.log('连接服务器成功...')
      $t.mtClientInited = true;
      $t.mtConning = false;
      if ($t.mtSubTmp.length > 0) {
        $t.mtSubscribe($t.mtSubTmp);
      }
    });
    //接收消息
    $t.mtClient.on('message', function (topic, message) {
      topic = topic.replace($t.globalData.topicPre, "");
      console.log(topic + ":" + message);
      try {
        let obj = JSON.parse(message);
        if (obj == null || obj["type"] == null || obj["type"] == undefined) {
          return;
        }
        if (obj["u"] != null && obj["u"] != $t.globalData.sid) {
          return;
        }
        if (obj.msg != null && (typeof obj.msg === "string") && obj.msg.startsWith("hz|")) {
          let arr = obj.msg.split("|");
          let newObj = {};
          for (var i = 1; i < msgKeyMap.length; i++) {
            if (arr.length > i) {
              newObj[msgKeyMap[i]] = arr[i];
            } else {
              break;
            }
          }
          obj.msg = newObj;
        }
        $t.handleDeviceStatus(topic, obj)
        $t.chgStatus(topic, obj);
        wx.$event.emit(topic, obj);
        //console.log(`发送event消息：${topic},${JSON.stringify(obj)}`);
        if (obj.type == "status" || obj.type == "getVal") {
          obj.topic = topic;
          wx.$event.emit(obj.type, obj);
        }
      } catch (e) {
        console.log(e);
      }
    });
    //断线重连
    $t.mtClient.on("reconnect", function () {
      console.log("重新连接")
      $t.logErr('重新连接...')
    });
    // 连接断开后触发的回调 
    $t.mtClient.on("close", function () {
      console.log("已断开连接")
      $t.logErr('已断开连接...')
      $t.mtClientInited = false;
      $t.mtConning = false;
    });
    // 在收到 Broker（消息服务器） 发送过来的断开连接的报文时触发的回调，参数 packet 即为断开连接时接收到的报文。MQTT 5.0特性 
    $t.mtClient.on("disconnect", function (packet) {
      console.log("从broker接收到断开连接的报文：" + packet);
      $t.logErr("从broker接收到断开连接的报文：" + packet)
      $t.mtClientInited = false;
      $t.mtConning = false;
    });
    // 客户端脱机下线触发回调 
    $t.mtClient.on("offline", function () {
      console.log("您已断开连接，请检查网络");
      $t.logErr('您已断开连接，请检查网络...')
      $t.mtClientInited = false;
      $t.mtConning = false;
    });
    $t.mtClient.on("error", function (error) {
      console.log(error);
      $t.logErr('连接异常...', error)
    });
    //当客户端发送任何数据包时发出。这包括publish()以及MQTT用于管理订阅和连接的包 
    /*$t.mtClient.on("packetsend", (packet) => {
      console.log("客户端已发出报文", packet);
    });*/

    //当客户端接收到任何报文时发出。这包括来自订阅主题的信息包以及MQTT用于管理订阅和连接的信息 
    /*$t.mtClient.on("packetreceive", (packet) => {
      // 会在 client.on('message', function (topic, message, packet) {}); 之前触发
      console.log("客户端接收报文", packet);
    });*/

  },
  sendMtMsg(topicSend, type, msg, cb) {
    const $t = this;
    if ($t.mtClient == null || !$t.mtClientInited) {
      $t.logErr('sendMtMsg service not connected...', topicSend, type)
      console.log("service not connected...", topicSend, type);
      if (cb) {
        cb("service not connected...");
      }
      return;
    }
    let obj = {
      type: type,
      u: $t.globalData.sid
    };
    if (msg != null) {
      obj.msg = msg;
    }
    let msgStr = JSON.stringify(obj);
    $t.mtClient.publish($t.globalData.topicPre + topicSend, msgStr, {
      qos: 0,
      retain: false
    }, function (error) {
      if (error) {
        console.log(error)
        $t.logErr('sendMtMsg send error...', topicSend, type, error)
      }
      if (cb) {
        cb(error)
        return
      }
      if (!error) {
        console.log('Published:' + msgStr);
        $t.handleSpecialMqttMsg(topicSend, type)
      }
    });
  },
  mtSubscribe(topicArr) {
    const $t = this;
    if ($t.mtClient == null || !$t.mtClientInited) {
      console.log("service not connected...");
      $t.mtSubTmp = topicArr;
      return;
    }
    console.log("mtSubMap=" + JSON.stringify($t.mtSubMap) + ";tarr=" + JSON.stringify(topicArr));
    for (var i = 0; i < topicArr.length; i++) {
      let topicSub = topicArr[i].topicSub;
      let topicSend = topicArr[i].topicSend;
      if ($t.mtSubMap[topicSub] != undefined) {
        continue;
      }
      console.log("topicSub=" + topicSub);
      $t.mtClient.subscribe($t.globalData.topicPre + topicSub, {
        qos: 0
      }, function (error, granted) {
        if (error) {
          console.log("订阅失败:", error)
          $t.logErr('订阅失败...', topicSub, error)
        } else {
          $t.mtSubMap[topicSub] = 1;
          $t.sendMtMsg(topicSend, "online", null);
          console.log("已订阅：" + topicSub);
        }
      })
    }

  },
  initDeviceStatusMap() {
    this.deviceStatusMap = {};
    this.deviceVerMap = {};
    let dids = storageService.getDeviceIds()
    if (dids.length == 0) {
      return;
    }
    for (var i = 0; i < dids.length; i++) {
      let dobj = storageService.getDeviceInfo(dids[i])
      if (!comm.isEmptyObj(dobj)) {
        let autoRunCfg = storageService.getAutoRunCfg(dobj.deviceId)
        let isE = comm.isEmptyObj(autoRunCfg);
        this.deviceStatusMap[dobj.topicSub] = {
          did: dobj.deviceId,
          sRun: isE ? 0 : autoRunCfg.sRun,
          tRun: isE ? "" : autoRunCfg.tRun,
          syncType: isE ? 0 : autoRunCfg.syncType
        };
        this.initVerInfo(dids[i], dobj.deviceVer);
      }
    }
  },
  chgStatus(topic, obj) {
    const $t = this;
    if (obj.type != "status") {
      return;
    }
    let topicObj = this.deviceStatusMap[topic];
    if (comm.isEmptyObj(topicObj)) {
      return;
    }
    let title = obj.msg.tRun;
    if (comm.isEmpty(title) || title == "null") {
      title = "未同步";
      obj.msg.tRun = "未同步";
    }
    let syncType = (obj.msg.sT != null && obj.msg.sT != 0) ? obj.msg.sT : (title != '未同步' ? 1 : 0);
    //运行状态更新
    if (title != topicObj.tRun || obj.msg.sRun != topicObj.sRun || syncType != topicObj.syncType) {
      let autoRunCfg = storageService.getAutoRunCfg(topicObj.did)
      autoRunCfg.sRun = obj.msg.sRun;
      autoRunCfg.tRun = obj.msg.tRun;
      autoRunCfg.syncType = syncType;
      topicObj.sRun = obj.msg.sRun;
      topicObj.tRun = obj.msg.tRun;
      topicObj.syncType = syncType;
      storageService.saveAutoRunCfg(topicObj.did, autoRunCfg)
    }

    if (obj.msg.tempStart) { //温度更新
      let v1 = parseFloat(obj.msg.tempNow); //当前温度
      let v2 = parseFloat(obj.msg.tempStart); //启动温度
      let v3 = parseInt(obj.msg.tempDiff); //校准温度
      for (let i = 0; i < tempArr.length - 1; i++) {
        if (v2 <= tempArr[i] && v2 > tempArr[i + 1]) {
          v2 = i;
          break;
        }
      }
      v2 = v2 - v3;
      if (v1 > tempArr[0]) {
        v1 = "<0";
      } else if (v1 < tempArr[tempArr.length - 1]) {
        v1 = ">" + tempArr.length;
      } else {
        for (let i = 0; i < tempArr.length - 1; i++) {
          if (v1 <= tempArr[i] && v1 > tempArr[i + 1]) {
            v1 = i;
            break;
          }
        }
        v1 = v1 + v3;
      }
      obj.msg.tempNow = v1;
      topicObj.temperature = v1;
      if (topicObj.tempStart != v2 || topicObj.tempDiff != v3) {
        topicObj.tempStart = v2;
        topicObj.tempDiff = v3;
        storageService.saveTempInfo(topicObj.did, {
          fanStartTemp: v2,
          ntcDiffTemp: v3
        })
      }
    }
    if (obj.msg.v != null) { //版本号更新
      let vobj = this.deviceVerMap[topicObj.did];
      if (!comm.isEmptyObj(vobj) && vobj.ver != obj.msg.v) {
        this.initVerInfo(topicObj.did, obj.msg.v);
        let deviceObj = storageService.getDeviceInfo(topicObj.did)
        if (!comm.isEmptyObj(deviceObj)) {
          deviceObj.deviceVer = obj.msg.v;
          storageService.saveDeviceInfo(topicObj.did, deviceObj)
        }
      }
    }
  },


  // 取消订阅名为 test 的 Topic
  mtUnsubscribe(topic) {
    const $t = this;
    $t.mtClient.unsubscribe($t.globalData.topicPre + topic, function (error) {
      if (error) {
        console.log(error)
      } else {
        delete $t.mtSubMap[topic];
        console.log('已取消订阅')
      }
    })
  },
  mtStop(isLazy) {
    console.log("mtStop:" + isLazy);
    const $t = this;
    if ($t.mtClientInited) {
      if (isLazy == 1) {
        $t.mtConnTimeout = setTimeout(() => {
          $t.mtClient.end(true);
          $t.mtClientInited = false;
          $t.mtConning = false;
          $t.mtSubMap = {};
        }, 5000);
      } else {
        $t.mtClient.end(true);
        $t.mtClientInited = false;
        $t.mtConning = false;
        $t.mtSubMap = {};
      }
    }
  },
  initVerInfo(did, deviceVer) {
    let t = deviceVer.substring(0, 1);
    var arr = deviceVer.substring(1).split("_");
    var v1 = parseInt(arr[0].replace(".", ""));
    var v2 = arr.length > 1 ? parseInt(arr[1]) : 0;
    this.deviceVerMap[did] = {
      t: t,
      v: v1,
      s: v2,
      ver: deviceVer
    };
  },
  initMtConfig(obj) {
    if (!comm.isEmpty(obj.username)) {
      this.globalData.username = obj.username;
      this.globalData.password = obj.password;
      this.globalData.mtid = this.globalData.openid;
      this.globalData.mtaddr = "wxs://99666666.xyz/wss";
      this.globalData.topicPre = "HzLamp/";
    }
  },


  /**
   * 应用退出
   * 当应用被完全关闭时触发
   */
  onUnload: function () {
    this.log("app onUnload...")
    logger.info('应用退出');

    // 终止所有Worker
    workerManager.terminateAllWorkers().catch(e => {
      logger.error('终止Worker失败', e);
    });

    // 执行其他清理工作
    this.cleanup();
  },

  /**
   * 应用错误处理
   */
  onError: function (error) {
    this.logErr("app onError...", error)
    // 过滤掉reportRealtimeAction相关错误以及not support错误
    if (typeof error === 'string' &&
      (error.includes('reportRealtimeAction') ||
        error.includes('not support'))) {
      logger.warn('忽略非关键错误', error);
      return;
    }

    logger.error('应用发生错误', error);

    // 错误上报
    this.reportError(error);
  },

  /**
   * 未处理的Promise异常
   */
  onUnhandledRejection: function (res) {
    const {
      reason
    } = res;

    // 过滤掉reportRealtimeAction相关错误
    if (reason && typeof reason === 'string' &&
      (reason.includes('reportRealtimeAction') ||
        reason.includes('not support'))) {
      logger.warn('忽略非关键Promise异常', reason);
      return;
    }

    logger.error('未处理的Promise异常', res);
  },

  /**
   * 页面不存在错误
   */
  onPageNotFound: function (res) {
    this.logErr("app onPageNotFound...", res)
    logger.warn('页面不存在', res);

    // 跳转到首页
    wx.switchTab({
      url: '/pages/index/index'
    });
  },

  /**
   * 检查小程序更新
   */
  checkUpdate: function () {
    if (wx.canIUse('getUpdateManager')) {
      const updateManager = wx.getUpdateManager();

      updateManager.onCheckForUpdate(function (res) {
        if (res.hasUpdate) {
          logger.info('发现新版本');
        }
      });

      updateManager.onUpdateReady(function () {
        wx.showModal({
          title: '更新提示',
          content: '新版本已经准备好，是否重启应用？',
          success: function (res) {
            if (res.confirm) {
              updateManager.applyUpdate();
            }
          }
        });
      });

      updateManager.onUpdateFailed(function () {
        logger.warn('新版本下载失败');
      });
    }
  },

  /**
   * 初始化系统信息
   */
  initSystemInfo: function () {
    try {
      // 使用新的API代替wx.getSystemInfoSync()
      const deviceInfo = wx.getDeviceInfo();
      const windowInfo = wx.getWindowInfo();
      const appBaseInfo = wx.getAppBaseInfo();

      // 合并系统信息
      const systemInfo = {
        ...deviceInfo,
        ...windowInfo,
        ...appBaseInfo
      };

      this.globalData.systemInfo = systemInfo;
      logger.info('获取系统信息成功', systemInfo);

      // 设置适配信息
      this.setAdaptiveInfo(systemInfo);
    } catch (error) {
      logger.error('获取系统信息失败', error);
    }
  },

  /**
   * 设置适配信息
   */
  setAdaptiveInfo: function (systemInfo) {
    // 计算安全区域
    const {
      screenHeight,
      screenWidth,
      safeArea
    } = systemInfo;

    this.globalData.safeArea = safeArea;
    this.globalData.navBarHeight = 44; // 导航栏高度（单位px）
    this.globalData.statusBarHeight = systemInfo.statusBarHeight;
    this.globalData.capsulePosition = wx.getMenuButtonBoundingClientRect();

    // 计算导航栏高度
    const capsuleHeight = this.globalData.capsulePosition.height;
    const capsuleTop = this.globalData.capsulePosition.top;
    const navBarHeight = capsuleHeight + (capsuleTop - systemInfo.statusBarHeight) * 2;
    this.globalData.customNavBarHeight = navBarHeight;

    // 设置主题 - 使用新的API获取主题
    const appBaseInfo = wx.getAppBaseInfo();
    this.globalData.theme = appBaseInfo.theme || 'light';

    // 监听主题变化
    wx.onThemeChange((res) => {
      this.globalData.theme = res.theme;
    });
  },

  /**
   * 加载应用设置
   */
  loadAppSettings: function () {
    try {
      const settings = wx.getStorageSync('app_settings');
      this.globalData.settings = settings || this.getDefaultSettings();
      logger.info('加载应用设置成功');
    } catch (error) {
      logger.error('加载应用设置失败', error);
      this.globalData.settings = this.getDefaultSettings();
    }
  },

  /**
   * 获取默认设置
   */
  getDefaultSettings: function () {
    return {
      theme: 'auto', // 主题模式：auto, light, dark
      language: 'zh_CN', // 语言：zh_CN, en_US
      enableNotification: true, // 是否启用通知
      bluetoothAutoConnect: true, // 蓝牙自动连接
      keepScreenOn: false, // 保持屏幕常亮
      enableSoundEffect: true, // 启用音效
      lightAdjustmentSpeed: 'normal', // 灯光调整速度：slow, normal, fast
      lightAnimationSpeed: 'normal', // 灯光动画速度：slow, normal, fast
    };
  },

  /**
   * 保存应用设置
   */
  saveAppSettings: function () {
    try {
      wx.setStorageSync('app_settings', this.globalData.settings);
      logger.info('保存应用设置成功');
    } catch (error) {
      logger.error('保存应用设置失败', error);
    }
  },

  /**
   * 保存应用状态
   */
  saveAppState: function () {
    /*try {
      const appState = {
        timestamp: Date.now(),
        //currentDevice: BluetoothService().getCurrentDevice(),
        // 保存其他状态
      };
      
      wx.setStorageSync('app_state', appState);
      logger.info('保存应用状态成功');
    } catch (error) {
      logger.error('保存应用状态失败', error);
    }*/
  },

  /**
   * 恢复应用状态
   */
  resumeAppState: function () {
    /*try {
      const appState = wx.getStorageSync('app_state');
      
      if (appState && appState.timestamp) {
        // 检查状态是否过期（1小时）
        const isExpired = Date.now() - appState.timestamp > 3600000;
        
        if (!isExpired) {
          logger.info('恢复应用状态成功');
          
          // 恢复蓝牙连接
          //this.resumeBluetoothConnection(appState);
        } else {
          logger.info('应用状态已过期');
        }
      }
    } catch (error) {
      logger.error('恢复应用状态失败', error);
    }*/
  },

  /**
   * 恢复蓝牙连接
   */
  /*resumeBluetoothConnection: function (appState) {
    if (this.globalData.settings.bluetoothAutoConnect && appState.currentDevice) {
      // 自动重连上次的蓝牙设备
      const deviceId = appState.currentDevice.deviceId;
      
      if (deviceId) {
        logger.info('尝试自动重连蓝牙设备', deviceId);
        
        BluetoothService().connectDevice(deviceId, {
          onConnected: (res) => {
            logger.info('自动重连蓝牙设备成功', res);
          },
          onFailed: (err) => {
            logger.warn('自动重连蓝牙设备失败', err);
          }
        });
      }
    }
  },*/

  /**
   * 设置调试模式
   */
  setDebugMode: function () {
    // 开发环境启用调试日志
    const envVersion = __wxConfig.envVersion;
    const isDevEnv = envVersion === 'develop' || envVersion === 'trial';

    if (isDevEnv) {
      logger.setLevel('DEBUG');
      logger.debug('启用调试模式');
    } else {
      logger.setLevel('INFO');
    }
  },

  /**
   * 上报错误信息
   */
  reportError: function (error) {
    // 实现错误上报逻辑
    // ...
  },

  /**
   * 应用清理工作
   */
  cleanup: function () {
    // 资源释放和状态重置
    try {
      // 关闭蓝牙连接
      /*const bluetooth = BluetoothService();
      if (bluetooth) {
        bluetooth.closeAll();
      }*/

      // 清理缓存数据
      this.clearTempData();

      logger.info('应用资源清理完成');
    } catch (e) {
      logger.error('应用清理失败', e);
    }
  },

  /**
   * 清理临时数据
   */
  clearTempData: function () {
    try {
      wx.removeStorageSync('temp_data');
      logger.info('临时数据清理完成');
    } catch (e) {
      logger.error('清理临时数据失败', e);
    }
  },
  log() {
    realLog.info(this.globalData.logPre, ...arguments)
  },
  logErr() {
    realLog.error(this.globalData.logPre, ...arguments)
  },
  logWarn() {
    realLog.warn(this.globalData.logPre, ...arguments)
  },
  handleSpecialMqttMsg(topic, type) {
    if ("chgAutoRun" === type || "syncDataUp" === type || "updateTemp" === type) {
      this.logWarn("special mqtt msg ", topic, type)
    }
  },
  checkMqttConnected() {
    return this.mtClientInited
  },

  /**
   * 全局数据
   */
  globalData: {
    // 用户信息
    userInfo: null,

    // 系统信息
    systemInfo: null,

    // 安全区域
    safeArea: null,

    // 导航栏高度
    navBarHeight: 44,

    // 状态栏高度
    statusBarHeight: 20,

    // 胶囊按钮位置
    capsulePosition: null,

    // 自定义导航栏高度
    customNavBarHeight: 64,

    // 当前主题
    theme: 'light',

    // 应用设置
    settings: null,

    // 启动参数
    launchOptions: null,

    // 设备信息
    devices: [],

    // 编组信息
    groups: [],

    // 设备服务
    deviceService: null,

    // 网络类型
    networkType: 'unknown',

    // 网络管理器
    networkManager: null,

    // 是否在开发者工具中运行
    isDevTools: false,





    model: null,
    pixelRatio: null,
    windowWidth: null,
    windowHeight: null,
    language: null,
    version: null,
    platform: null,
    loginPromise: null,
    openid: null,
    sid: null,
    domain: domain,
    username: "beid_3MjNxgDN0UzNx8VNzMDM3ED",
    password: "7b22hmXAXsphvg2CiUFN779fUZwWWxvi",
    mtid: "",
    mtaddr: "wxs://bemfa.com:9504/wss",
    deviceIp: "",
    devicePort: "",
    tempArr: tempArr,
    isAdding: false,
    topicPre: "",
  },




  ckOnlineInterval: null,
  onlineMap: {
    /*"topic":"lastTime"*/
  },
  handleDeviceStatus(topic, msgObj) {
    if (this.onlineMap[topic] == null) {
      this.onlineMap[topic] = Date.now()
      wx.$event.emit("EventOnline", topic);
      console.log(topic + " switch online")
    } else {
      this.onlineMap[topic] = Date.now()
    }
  },
  handleOffline() {
    const now = Date.now()
    for (let key in this.onlineMap) {
      if ((now - this.onlineMap[key]) / 1000 > 15) {
        delete this.onlineMap[key]
        wx.$event.emit("EventOffline", key)
        console.log(key + " switch offline")
      }
    }
  },
  checkIsOnline(topic) {
    return this.onlineMap[topic] != null
  },
  getTemperature(topic) {
    const topicObj = this.deviceStatusMap[topic]
    if (comm.isEmptyObj(topicObj)) {
      return -99
    }
    const temperature = topicObj["temperature"]
    if (comm.isEmpty(temperature)) {
      return -99
    }
    return temperature
  },
  getTemperatureStr(topic) {
    const temperature = this.getTemperature(topic)
    if (temperature === -99) {
      return "--"
    }
    return temperature + ""
  },




});